package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Appointment;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.AppointmentMapper;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.StatementItemQuery;
import cn.wolfcode.car.business.query.StatementQuery;
import cn.wolfcode.car.business.service.IStatementItemServicePlus;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import net.minidev.json.writer.UpdaterMapper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

@Service
@Transactional
public class StatementItemServiceImplPlus extends ServiceImpl<StatementItemMapper,StatementItem> implements IStatementItemServicePlus {
    @Autowired
    private StatementMapper statementMapper;
    @Autowired
    private StatementItemMapper statementItemMapper;
    @Autowired
    private AppointmentMapper appointmentMapper;

    @Override
    public TablePageInfo<StatementItem> query(StatementItemQuery qo) {
        IPage<StatementItem> page = new Page<>(qo.getPageNum(),qo.getPageSize());
        QueryWrapper<StatementItem> wrapper = new QueryWrapper<>();
        wrapper.eq(qo.getStatementId() != null,"statement_id",qo.getStatementId());
        return new TablePageInfo<StatementItem>(super.page(page,wrapper));
    }

    @Override
    public void saveItems(List<StatementItem> items) {
        //集合中的最后一个元素只是为了保存价格，因此把最后一个元素删除只获取到其优惠价格即可
        //获取优惠价格
        //通过结算单id获取结算单对象
        //在进行保存操作时，需要先将原来已经存在的结算单明细数据删除都删除，在插入更新后的数据
        //定义总金额和总数量的变量
        //循环过程中把结算单明细插入表中
        //判断折扣金额是否大于总金额
        //通过结算单id更新结算单相关数据
        StatementItem tempItem = items.remove(items.size() - 1);
        BigDecimal disCountPrice = tempItem.getItemPrice();
        System.out.println(disCountPrice);
        Statement statement = statementMapper.selectById(tempItem.getStatementId());
        if(!Statement.STATUS_CONSUME.equals(statement.getStatus())){
            throw new BusinessException("只有是消费中的结算单才可进行结算单明细的保存");
        }
        QueryWrapper<StatementItem> wrapper = new QueryWrapper<>();
        wrapper.eq("statement_id",statement.getId());
        statementItemMapper.delete(wrapper);
        BigDecimal totalAmount = new BigDecimal(0);
        BigDecimal totalQuantity = new BigDecimal(0);
        if(items.size() > 0){
            for (StatementItem item : items) {
                statementItemMapper.insert(item);
                totalAmount = totalAmount.add(item.getItemPrice().multiply(item.getItemQuantity()));
                totalQuantity = totalQuantity.add(item.getItemQuantity());
            }
        }
        if(disCountPrice.compareTo(totalAmount) > 0){
            throw new BusinessException("优惠金额不能小于总金额");
        }
        //通过结算单id更新结算单相关数据
        UpdateWrapper<Statement> wrapper1 = new UpdateWrapper<>();
        wrapper1.eq("id", statement.getId())
                .set("total_amount",totalAmount)
                .set("total_quantity",totalQuantity)
                .set("discount_amount",disCountPrice);
        statementMapper.update(null,wrapper1);
    }

    @Override
    public void payStatement(Long statementId) {
        //如果该状态为消费中，才可点击确认支付
        //成功，将状态修改为已支付
        //支付时间在sql语句中进行通过now()函数进行更新
        //如果结算单是预约单生成的,需要根据预约单ID更新预约单的状态为已结算
        //如果预约单id不为空，说明是由预约单生成的，需要根据预约单ID更新预约单的状态为结算单生成
        // 说明是预约单生成的
        Statement statement = statementMapper.selectById(statementId);
        if(Statement.STATUS_PAID.equals(statement.getStatus())){
            throw new BusinessException("已支付的结算单不能重复支付");
        }
        //statementMapper.updatePayStatement(statementId,Statement.STATUS_PAID, ShiroUtils.getUserId());
        UpdateWrapper<Statement> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", statementId)
                .set("status", Statement.STATUS_PAID)
                .set("payee_id",ShiroUtils.getUserId());
        statementMapper.update(null,wrapper);
        Long appointmentId = statement.getAppointmentId();
        if(appointmentId != null){
            //说明是预约单生成的
            UpdateWrapper<Appointment> wrapper1 = new UpdateWrapper<>();
            wrapper1.eq("id",appointmentId)
                    .set("status", Appointment.STATUS_SETTLE);
            appointmentMapper.update(null,wrapper1);
        }

    }
}
